<template>
  <div class="viewContain">
    <div class="delivery">
      <el-form ref="form" :model="form" label-width="">
        <el-form-item label="请选择发货地：">
          <el-select v-model="areaId" filterable clearable placeholder="请选择" size="mini" style="width: 215px" @change="selectArea">
            <el-option
              v-for="item1 in areaList"
              :key="item1.value"
              :label="item1.label"
              :value="item1.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="请选择发货地：">
          <el-radio-group v-model="deliverInfo.radio" size="small">
            <el-radio v-for="item in areaList" :key="item.id" style="margin-bottom:10px" :label="item.id" border>{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <div v-for="(item, index) in selectGoodsList" :key="index" class="list">
          <el-row>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
              <el-form-item :label="'发货物品' + (index+1) + ':'" size="mini">
                <el-select
                  v-model="item.id"
                  style="width: 400px"
                  size="mini"
                  filterable
                  clearable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="remoteMethod"
                  :loading="loadingGoods"
                  @change="changeGoods"
                >
                  <el-option
                    v-for="item1 in options"
                    :key="item1.value"
                    :label="item1.label"
                    :value="item1.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="{ span: 24 }" :sm="{ span: 4 }" :md="{ span: 4 }" :xl="{ span: 4 }">
              <el-input-number v-model="item.num" size="mini" :min="1" :max="9999" label="描述文字" :step-strictly="true" @change="handleChange" />
            </el-col>
            <el-col :xs="{ span: 24 }" :sm="{ span: 4 }" :md="{ span: 4 }" :xl="{ span: 4 }">
              <el-button type="danger" size="mini" @click="deleteItem(index)">删除</el-button>
            </el-col>
          </el-row>
        </div>
        <div class="operate" style="margin-bottom: 10px">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="addGoods">新增商品</el-button>
          <el-button type="primary" size="mini" icon="el-icon-refrigerator" @click="startCalculate">开始计算</el-button>
        </div>
      </el-form>
      <div v-if="isShow" v-loading="calLoading" class="resultBox">
        <div class="result">
          <span v-for="item in result" :key="item.id" class="item">
            <span>{{ item.deliveryName }} : {{ item.totalPrice }}元</span>
          </span>
          <span class="item">
            <span>安能物流 : {{ totalPrice_anneng }}元</span>
          </span>
          <span class="item">
            <span>中通快运 : {{ totalPrice_zt }}元</span>
          </span>
          <span class="item">
            <span>德邦物流 : {{ totalPrice_db }}元</span>
          </span>
          <div class="recomend">系统推荐:
            <!-- <span>{{ bestDelivery }}</span> -->
            <span>{{ resName }}</span>
          </div>

        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getDeliveryPrice, provinceList, goodsList, annengList, zhongtongKYList, debangWLList } from '@/api/index'

export default {
  data() {
    return {
      activeName: 'first',
      test: '',
      calLoading: false,
      areaId: '',
      address: [],
      loadingGoods: false,
      form: {},
      num: 0,
      listQuery: {
        pageNum: 1,
        pageSize: 9999,
        goodsName: ''

      },
      listQuery_goods: {
        pageNum: 1,
        pageSize: 9999,
        goodsName: ''
      },
      goodsList: [], // 商品列表-接口返回
      goodsLists: [], // 商品列表-下拉
      areaList: [],
      deliverInfo: {
        radio: '',
        inputWeight: ''
      },
      tableData: [],
      priceList: [],
      selectData: [],
      isShow: false,
      recomendRes: {},
      commonPrice: '', // 通票价格
      goodsName: '',
      options: [],
      selectGoodsList: [
        {
          id: '',
          num: 0
        }
      ],
      result: [],
      bestDelivery: '',
      resName: '',
      // guangdongPriceAN: [{ id: 1, area: '', areaCode: '', heavyGoods: 0.65, lightGoods: 130, startPrice: 30 }],
      guangdongPriceAN: [],
      guangdongPriceZT: [],
      guangdongPriceDB: [],
      totalPrice_anneng: 0,
      totalPrice_zt: 0, // 中通快运的价格
      totalPrice_db: 0, // 德邦物流的价格
      logisticsList: [],
      annengList: [], // 安能配置表
      zhongtongKYList: [], // 中通快运物流配置表
      debangWLList: [], // 中通快运物流配置表
      firstWeightZT: 10, // 中通首重10kg
      firstWeightDB: 30, // 德邦首重30kg
      firstWeightBisic: 30, // 德邦单票30kg
      jipao: 10000, // 快递计抛系数
      jipao_anneng: { // 安能物流计抛系数
        level1: 12000,
        level2: 8000,
        level3: 6000
      },
      jipaoZT: 5000, // 中通快运计抛
      jipaoDB: 6000, // 德邦物流计抛
      commonWeight: 3, // 快递通票
      yundaConfig: {
        level1: 2.55,
        level2: 3.25,
        level3: 4.45,
        level4: 5.95
      }
    }
  },
  watch: {

  },
  created() {
  },
  mounted() {
    this.getList()
    this.getAddressList()
    this.getGoodsList()
    // 获取物流配置
    this.getListAN()
    this.getListZTKY()
    this.getListDB()
  },
  methods: {
    handleClick() {
      this.startCalculate()
    },
    changeGoods(val) {
      // console.log('选中值的变化===', val)
      // console.log('this.goodsList===', this.goodsList)
      this.weigth = this.goodsList.filter(item => item.id === val)[0].goodsWeight
      // console.log('this.weigth===', this.weigth)
    },
    handleChange(val) {
      this.isShow = false
    },
    // 新增商品
    addGoods() {
      this.selectGoodsList.push({
        id: '',
        num: 0
      })
      this.isShow = false
    },
    deleteItem(index) {
      if (this.selectGoodsList.length === 1) {
        this.$message({
          type: 'warning',
          message: '请至少保留一个商品!'
        })
        return
      }
      this.isShow = false
      this.selectGoodsList.splice(index, 1)
    },
    getGoodsList() {
      goodsList(this.listQuery_goods).then(res => {
        if (res.code === 200) {
          // const arr = []
          this.goodsList = res.data.list
          res.data.list.forEach(item => {
            this.goodsLists.push({ value: item.id, label: item.goodsName })
          })
          // console.log('this.goodsLists===', this.goodsLists)
        }
      })
    },
    startCalculate() {
      this.logisticsList = []
      console.log('this.selectGoodsList===', this.selectGoodsList)
      if (!this.areaId) {
        alert('请选择发货地!')
        return
      }
      this.selectGoodsList.forEach((item, index) => {
        if (!item.id) {
          alert(`请选择发货物品${index + 1}`)
          return
        }
      })

      // 查找该地区是否用安能物流在营运
      const isHasAnneng = this.annengList.some(item => item.areaCode === this.areaId)
      if (!isHasAnneng) {
        alert('该地区暂无安能物流配送信息!请前往后台配置！')
        this.isShow = false
        return
      }

      // 查找该地区是否用中通快运在营运
      console.log('this.zhongtongKYList===', this.zhongtongKYList)
      const isHaszhongtongKY = this.zhongtongKYList.some(item => item.areaCode === this.areaId)
      if (!isHaszhongtongKY) {
        alert('该地区暂无中通快运物流配送信息!请前往后台配置！')
        this.isShow = false
        return
      }

      // 查找该地区是否用德邦物流在营运
      const isHasdebang = this.debangWLList.some(item => item.areaCode === this.areaId)
      if (!isHasdebang) {
        alert('该地区暂无德邦物流配送信息!请前往后台配置！')
        this.isShow = false
        return
      }

      const hasEveryId = this.selectGoodsList.every((item) => item.id !== '')
      if (hasEveryId) {
        this._isCommonTiket1() // 快递计算
        this.logistics() // 物流计算
      }
    },
    selectArea(e) {
      this.isShow = false
      const arr = this.annengList.filter(item => {
        return item.areaCode === e
      })
      this.guangdongPriceAN = arr

      const arr1 = this.zhongtongKYList.filter(item => {
        return item.areaCode === e
      })
      this.guangdongPriceZT = arr1

      const arr2 = this.debangWLList.filter(item => {
        return item.areaCode === e
      })
      this.guangdongPriceDB = arr2

      console.log(arr1)
      console.log(arr2)
    },
    // 物流计算
    logistics() {
      // 安能物流
      this.anneng()
      this.zhongtongKY()
      this.debangWL()
      setTimeout(() => {
        this.logisticsContract()
      }, 500)
    },
    logisticsContract() {
      console.log('this.logisticsList===', this.logisticsList)
      const priceList = []
      this.logisticsList.forEach(item => { priceList.push(item.price) })
      var min = Math.min(...priceList)
      console.log(min)
      const index = this.logisticsList.findIndex(item => item.price === min)
      console.log(index)
      this.resName = this.logisticsList[index].name
    },
    anneng() {
      // 价格低于起步价，按起步价+5
      // 1-60KG  （实重*重货（元/公斤））+5
      // 70-800KG  （实重*重货（元/公斤））*0.9+5

      // 这里需要新建一个物流专属的物流价格列表
      const targetGoods = this.guangdongPriceAN
      // console.log('this.selectGoodsList===', this.selectGoodsList)
      const priceList = []
      this.selectGoodsList.forEach(item => {
        this.goodsList.forEach(item1 => {
          if (item.id === item1.id) {
            console.log(item1)
            // 重货： 重量×续重，
            const goodsWeight = this.beforeCalculate(item1, 'logistics_anneng')

            // 1-60KG（实重*重货（元/公斤））+5
            // 70-800KG（实重*重货（元/公斤））*0.9+5
            console.log('goodsWeight===', goodsWeight)
            let heavyGoods
            if (goodsWeight >= 1 && goodsWeight <= 60) {
              heavyGoods = (item1.goodsWeight * targetGoods[0].heavyGoods + 5) * item.num
            } else if (goodsWeight >= 70 && goodsWeight <= 800) {
              heavyGoods = (item1.goodsWeight * targetGoods[0].heavyGoods * 0.9 + 5) * item.num
            }
            // console.log('heavyGoods===', heavyGoods)

            // 轻货: 体积×轻货价格
            const volume = (item1.goodsLength / 100) * (item1.goodsWidth / 100) * (item1.goodsHeight / 100)
            const lightGoods = (volume * targetGoods[0].lightGoods) * item.num
            console.log('lightGoods===', lightGoods)
            // 谁贵算谁
            const price = heavyGoods > lightGoods ? heavyGoods : lightGoods
            console.log('最终选择的价格===', price)
            priceList.push(Number(price.toFixed(2)))
          }
        })
      })
      console.log('priceList===', priceList)
      const sum = priceList.reduce((x, y) => { return x + y })
      // 价格低于起步价，按起步价+5
      const startPrice = targetGoods[0].startPrice
      const totalPrice_anneng = sum < startPrice ? startPrice + 5 : sum.toFixed(2)
      this.totalPrice_anneng = totalPrice_anneng
      console.log('安能最终的价格===', totalPrice_anneng)
      this.logisticsList.push({ name: '安能物流', price: Number(totalPrice_anneng) })
    },
    zhongtongKY() {
      // 30kg以上(含30kg）核算公式：(实重-首重)*续重
      // 30kg以下核算公式：(实重-首重10kg)*续重+首重
      // 收费以体积计泡重量或实际重量两者对比大者为准,计泡标准:长*宽*高/5000
      const targetGoods = this.guangdongPriceZT
      const { firstWeight, secondWeight } = targetGoods[0]
      console.log('this.selectGoodsList===', this.selectGoodsList)
      // guangdongPriceDB: [{ id: 1, area: '', areaCode: '', firstWeight: 97, secondWeight: 1.96 }],
      const priceList = []
      this.selectGoodsList.forEach(item => {
        this.goodsList.forEach(item1 => {
          if (item.id === item1.id) {
            console.log('item1===', item1)
            const goodsWeight = this.beforeCalculate(item1, 'logistics_debang')
            console.log('goodsWeight===', goodsWeight)
            let price
            if (goodsWeight >= this.firstWeightBisic) {
              const singlePrice = (goodsWeight - firstWeight) * secondWeight
              price = singlePrice * item.num
            } else {
              // console.log(goodsWeight)// 3.75
              // console.log(firstWeight)// 17
              // console.log(secondWeight) // 1.4

              const singlePrice = (goodsWeight - this.firstWeightZT) * secondWeight + firstWeight
              price = singlePrice * item.num
            }
            priceList.push(Number(price.toFixed(2)))
          }
        })
      })
      console.log('priceList===', priceList)
      const sum = priceList.reduce((x, y) => { return x + y })
      this.totalPrice_zt = sum.toFixed(2)
      console.log('中通快运最终的价格===', sum)
      this.logisticsList.push({ name: '中通快运', price: Number(sum.toFixed(2)) })
    },
    debangWL() {
      // (实重-30kg首重)*续重+首重 单票起步30Kg 不足30kg的按30来算
      const targetGoods = this.guangdongPriceDB
      const { firstWeight, secondWeight } = targetGoods[0]
      console.log(firstWeight)
      console.log('this.selectGoodsList===', this.selectGoodsList)
      // guangdongPriceDB: [{ id: 1, area: '', areaCode: '', firstWeight: 10, secondWeight: 0.5 }]
      const priceList = []
      this.selectGoodsList.forEach(item => {
        this.goodsList.forEach(item1 => {
          if (item.id === item1.id) {
            console.log('item1===', item1)
            let goodsWeight = this.beforeCalculate(item1, 'logistics_zhongtong')
            console.log('goodsWeight===', goodsWeight)
            let price
            if (goodsWeight >= this.firstWeightBisic) {
              const singlePrice = (goodsWeight - this.firstWeightDB) * secondWeight + firstWeight
              price = singlePrice * item.num
            } else {
              console.log('不满30kg===')
              goodsWeight = 30
              const singlePrice = (goodsWeight - this.firstWeightDB) * secondWeight + firstWeight
              price = singlePrice * item.num
            }
            priceList.push(Number(price.toFixed(2)))
          }
        })
      })
      console.log('priceList===', priceList)
      const sum = priceList.reduce((x, y) => { return x + y })
      this.totalPrice_db = sum.toFixed(2)
      console.log('德邦物流最终的价格===', sum)
      this.logisticsList.push({ name: '德邦物流', price: Number(sum.toFixed(2)) })
    },

    /**
     *  计抛计算
     * （长cm*宽cm*高cm）/10000
     *  eg: 一台BF501重量为15kg 计抛折算为（50*50*100）/10000 = 25   25>15  所以出货重量按照25kg来计算
     */
    beforeCalculate(goodsInfo, type) {
      // 商品参数: 长度，宽度，高度，型号，名称
      var { goodsLength, goodsWidth, goodsHeight, goodsWeight } = goodsInfo
      // 计算体积(立方米)
      const volume = (goodsLength / 100) * (goodsWidth / 100) * (goodsHeight / 100)
      const jipao = this.jipaoCalculate(type, goodsWeight)
      if ((volume * jipao) > goodsWeight) {
        goodsWeight = volume * jipao
      }
      return goodsWeight
    },
    /**
     * 安能体积重计算方式：
     * 30公斤以内:长*宽*高/12000=公斤,1立方=84公斤
     * 30-70公斤:长*宽*高/8000=公斤，1立方=125公斤
     * 70公斤以上:长*宽*高/6000=公斤，1立方=167公斤
     */
    jipaoCalculate(type, goodsWeight) {
      const { level1, level2, level3 } = this.jipao_anneng
      if (type === 'logistics_anneng') {
        // 安能物流计抛
        if (goodsWeight < 30) {
          return (100 * 100 * 100) / level1
        } else if (goodsWeight >= 30 && goodsWeight <= 70) {
          return (100 * 100 * 100) / level2
        } else if (goodsWeight > 70) {
          return (100 * 100 * 100) / level3
        }
      } else if (type === 'logistics_zhongtong') {
        return (100 * 100 * 100) / this.jipaoZT
      } else if (type === 'logistics_debang') {
        return (100 * 100 * 100) / this.jipaoDB
      } else {
        // 快递计抛
        return (100 * 100 * 100) / this.jipao // 100kg/m³
      }
    },

    // 根据数量来计算
    _isCommonTiket1() {
      // 筛选出来的地区areaId，去匹配快递价格配置表，得到该地区对应的快递价格明细
      // console.log('this.tableData===', this.tableData)
      const selectData = this.tableData.filter(item => item.areaCode === this.areaId)
      // console.log('selectData===', selectData)
      const deliveryList = []
      selectData.forEach(item => deliveryList.push(item.deliveryName))
      this.selectData = selectData
      const priceList = []
      this.selectGoodsList.forEach(item2 => {
        this.goodsList.forEach(item3 => {
          if (item3.id === item2.id) {
            selectData.forEach((item) => {
              const goodsWeight = this.beforeCalculate(item3, 'delivery')
              // console.log('goodsWeight===', goodsWeight)
              if (goodsWeight <= this.commonWeight) {
                // 通票逻辑
                const price = (this.isCommonTiket(item, goodsWeight)) * item2.num
                priceList.push(price)
              } else {
                // 计抛逻辑
                item2.price = (item.secondWeight * goodsWeight + item.firstWeight) * item2.num
                item2.price = Number(item2.price.toFixed(2))
                priceList.push(item2.price)
              }
            })
          }
        })
      })
      console.log('priceList===', priceList)
      const getNewArray = this.getNewArray(priceList, selectData.length)
      console.log('分割后的结果getNewArray===', getNewArray)
      const sumArray = this.sumArray(getNewArray)
      console.log('分割后的单个快递计算综合sumArray===', sumArray)
      const index = this.getMinIndex(sumArray)
      const bestDelivery = selectData[index].deliveryName
      console.log('最合适的快递为====', bestDelivery)
      this.bestDelivery = bestDelivery
      console.log('数组重新组合deliveryList===', deliveryList)
      const res = []
      deliveryList.forEach((_item, _index) => {
        sumArray.forEach((item_, index_) => {
          if (_index === index_) {
            res.push({
              deliveryName: _item,
              totalPrice: item_.toFixed(2)
            })
            this.logisticsList.push({
              name: _item,
              price: Number(item_.toFixed(2))
            })
          }
        })
      })
      console.log('res===', res)
      this.result = res
      if (this.areaId) {
        setTimeout(() => { this.isShow = true }, 500)
      } else {
        this.isShow = false
      }
    },
    /**
     * 通票判断
     * 这里分为圆通和韵达
     */
    isCommonTiket(item, goodsWeight) {
      // console.log('goodsWeight===', goodsWeight)
      // console.log('item===', item)
      console.log('走通票===')
      const { level1, level2, level3, level4 } = this.yundaConfig
      if (item.deliveryName === '韵达快递') {
        if (goodsWeight > 0 && goodsWeight <= 0.5) {
          return level1
        } else if (goodsWeight > 0.5 && goodsWeight <= 1) {
          return level2
        } else if (goodsWeight > 1 && goodsWeight <= 2) {
          return level3
        } else if (goodsWeight > 2 && goodsWeight <= 3) {
          return level4
        }
      } else if (item.deliveryName === '圆通快递') {
        return 3
      }
    },
    // 快递价格配置表
    getList() {
      this.loading = true
      getDeliveryPrice(this.listQuery).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.list
          this.loading = false
        } else {
          this.loading = false
        }
      })
    },
    // 地区配置表
    getAddressList() {
      const params = { pageNum: 1, pageSize: 50 }
      provinceList(params).then(res => {
        // console.log('res===', res)
        if (res.code === 200) {
          const arr = []
          res.data.list.forEach(item => {
            arr.push({ value: item.id, label: item.name })
          })
          this.areaList = arr
          // console.log('this.areaList===', this.areaList)
        }
      })
    },
    // 数组分割
    getNewArray(array, subGroupLength) {
      let index = 0
      const newArray = []
      while (index < array.length) {
        newArray.push(array.slice(index, index += subGroupLength))
      }
      return newArray
    },
    // 将数组中相同索引处的元素求和到单个数组中
    sumArray(array) {
      const newArray = []
      array.forEach(sub => {
        sub.forEach((num, index) => {
          if (newArray[index]) {
            newArray[index] += num
          } else {
            newArray[index] = num
          }
        })
      })
      return newArray
    },
    // 获取最小值的下标
    getMinIndex(arr) {
      var min = arr[0]
      var index = 0
      for (var i = 0; i < arr.length; i++) {
        if (min > arr[i]) {
          min = arr[i]
          index = i
        }
      }
      return index
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loadingGoods = true
        setTimeout(() => {
          this.loadingGoods = false
          this.options = this.goodsLists.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1
          });
        }, 200)
      } else {
        this.options = []
      }
    },
    getListAN() {
      this.loading = true
      const params = { pageNum: 1, pageSize: 999 }
      annengList(params).then(res => {
        if (res.code === 200) {
          this.annengList = res.data.list
        }
      })
    },
    getListZTKY() {
      this.loading = true
      const params = { pageNum: 1, pageSize: 999 }
      zhongtongKYList(params).then(res => {
        if (res.code === 200) {
          this.zhongtongKYList = res.data.list
        }
      })
    },
    getListDB() {
      this.loading = true
      const params = { pageNum: 1, pageSize: 999 }
      debangWLList(params).then(res => {
        if (res.code === 200) {
          this.debangWLList = res.data.list
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .viewContain {
    .result {
      margin-top: 20px;
      .item {
        margin-right: 20px;
      }
      .recomend {
        span {
          color: red;
          font-size: 20px;
        }
      }
    }
    .resultBox {
      margin-top: 20px;
      border-radius: 10px;
      width: 1000px;
      height: 200px;
      border: 1px solid #ccc;
      .result {
        margin-top: 20px;
        .item {
          margin-right: 20px;
        }
        .recomend {
          margin-top: 20px;
          margin-left: 2px;
          span {
            color: red;
            font-size: 20px;
          }
        }
      }
    }
  }
</style>

